var canvas = document.getElementById('clockCanvas');
var context = canvas.getContext('2d');
var canvasWidth = parseFloat(getComputedStyle(canvas).width);
var canvasHeight = parseFloat(getComputedStyle(canvas).height);
canvas.height = canvasHeight;
canvas.width = canvasWidth;
var centerX = canvas.width/2; //画布的中心x轴坐标
var centerY = canvas.height/2; //画布的中心y轴坐标
var radius = centerX - 10; //时钟的半径
var isdrag = false; //是否被拖拽
var option = false; //是否在进行操作
var dragtarget = ""; //当前被拖拽的对象
var now = new Date(); //获取当前时间
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var time = hours>=0 && hours < 12 ? "am" : "pm"
var ischange = false;
var hourAngle; //时针的角度
var minuteAngle; //分针的角度
var color = "white" //时钟的颜色
var colors = ["black", "white", "grey", "yellow"]; //用于切换的颜色列表
var clocklist = []; //定下的闹钟列表
var clocklist1 = document.getElementById("clocklist"); // 用于在页面上显示闹钟信息

function update(){
    if (option == false){
        var now = new Date();   
        hours = now.getHours();
        minutes = now.getMinutes();
        seconds = now.getSeconds();
        time = hours>=0 && hours < 12 ? "am" : "pm";
        if(hours == 12 && minutes == 0){
            settime();
        }
        if(ischange){
            settime();
            ischange = false;
        }
        
        hourAngle = (hours % 12 + minutes / 60) * (Math.PI / 6);
        minuteAngle = (minutes + seconds / 60) * (Math.PI / 30);
        judgeclock();
    }
    DrawClock(hourAngle,minuteAngle);
    requestAnimationFrame(update);
}
function DrawClock(hourAngle,minuteAngle){

    drawbackground();
    context.lineWidth = 8;
    context.strokeStyle = color;
    context.beginPath();
    context.moveTo(centerX, centerY);
    context.lineTo(centerX + Math.sin(hourAngle) * radius * 0.5, centerY - Math.cos(hourAngle) * radius * 0.5);
    context.stroke();

    context.lineWidth = 4;
    context.strokeStyle = color;
    context.beginPath();
    context.moveTo(centerX, centerY);
    context.lineTo(centerX + Math.sin(minuteAngle) * radius * 0.7, centerY - Math.cos(minuteAngle) * radius * 0.7);
    context.stroke();
}

function drawbackground(){

    var radius = centerX - 10;

    context.clearRect(0, 0, canvas.width, canvas.height);

    //绘制圆盘作为基底
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    context.lineWidth = 6;
    context.strokeStyle = color;
    context.stroke();

    context.beginPath();
    context.arc(centerX, centerY, 10, 0, 2 * Math.PI);
    context.strokeStyle = color;
    context.fill();

    // 绘制刻度和数字
    context.font = "20px Arial";
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillStyle = color;

    for (var i = 1; i <= 12; i++) {
    var angle = (i - 3) * (Math.PI * 2) / 12; // 计算刻度的角度
    var x = centerX + Math.cos(angle) * (radius - 30); // 刻度所在位置的 x 坐标
    var y = centerY + Math.sin(angle) * (radius - 30); // 刻度所在位置的 y 坐标
    
    // 绘制刻度线段
    context.beginPath();
    context.moveTo(x, y);
    context.lineTo(centerX + Math.cos(angle) * (radius - 5), centerY + Math.sin(angle) * (radius - 5));
    context.lineWidth = 3;
    context.strokeStyle = color;
    context.stroke();

    // 绘制数字
    context.fillText(i.toString(), x - Math.cos(angle) * 15, y - Math.sin(angle) * 15);
    }
}

//判断鼠标是否在时针或分针上，如果是就可以开始拖拽
function ismouseonhands(event){
    var result = getmousexy(event);
    var newmousex = result.mousex - centerX;
    var newmousey = centerY - result.mousey;
    var minutedistance = Math.abs(Math.sin(minuteAngle)*(newmousey-newmousex/Math.tan(minuteAngle))); 
    var hourdistance = Math.abs(Math.sin(hourAngle)*(newmousey-newmousex/Math.tan(hourAngle)));
    if((minutedistance <= 4) && (Math.sin(minuteAngle)*newmousex >= 0) && (Math.cos(minuteAngle)*newmousey >= 0)){
        isdrag = true;
        option = true;
        dragtarget = "minute";
        console.log(isdrag, dragtarget);
        return ;
    }
    else if(hourdistance <= 8 && Math.sin(hourAngle)*newmousex >= 0 && Math.cos(hourAngle)*newmousey >= 0){
        isdrag = true;
        option = true;
        dragtarget = "hour";
        console.log(isdrag, dragtarget);
        return ; 
    }
    else console.log("false");
}

//获取鼠标的位置，这里传送的是相对于画布左上角的坐标而不是相对于中心的坐标，需要转换
function getmousexy(event){
    var rect = canvas.getBoundingClientRect();
    var mousex = event.clientX - rect.left;
    var mousey = event.clientY - rect.top;
    // console.log(mousex, mousey);
    return {mousex: mousex, mousey : mousey};
}

//这里描述了当鼠标移动时，时针和分针跟随转动的逻辑，小时和分都一起改变了
function mousemove(event){
    var result = getmousexy(event);
    var newmousex = result.mousex - centerX;
    var newmousey = centerY - result.mousey;
    if(isdrag == true){
        if(dragtarget == "hour"){
            if (newmousey >= 0 && newmousex >= 0){
                hourAngle = Math.atan(newmousex/newmousey);
            }
            else if(newmousey >= 0 && newmousex < 0){
                hourAngle = 2 * Math.PI + Math.atan(newmousex/newmousey);
            }
            else {
                hourAngle = Math.PI + Math.atan(newmousex/newmousey);
            }
            minuteAngle = hourAngle % (Math.PI/6) * 12; 
            hours = Math.floor(hourAngle/(Math.PI/6));
            minutes = Math.floor(minuteAngle/(Math.PI/30));
        }
        else if(dragtarget == "minute"){
            if (newmousey >= 0 && newmousex >= 0){
                minuteAngle = Math.atan(newmousex/newmousey);
            }
            else if(newmousey >= 0 && newmousex < 0){
                minuteAngle = 2 * Math.PI + Math.atan(newmousex/newmousey);
            }
            else {
                minuteAngle = Math.PI + Math.atan(newmousex/newmousey);
            }
            hourAngle =  (hours % 12 + minuteAngle/ 2 / Math.PI) * Math.PI / 6
            hours = hours % 12;
            minutes = Math.floor(minuteAngle/(Math.PI/30));
        }
    }
}

//停下时停止拖拽，但是option并未为真，因为我们后续还有设置闹钟的步骤未完成
function stopdrag(){
    isdrag = false;
    // console.log(hours,minutes);
}

//可以切换时钟的颜色
function switch1 () {
    var i = 0;
    while(color != colors[i]){
        i = i + 1;
    }
    // console.log(hours,minutes);
    color = colors[(i+1)%4];
}

//设置背景
function settime(){
    var bodyElement = document.body;
    if(time == "am"){
        if(hours >= 12){
            hours -= 12;
        }
        bodyElement.style.backgroundImage = 'url("../img/am/4.png")';
        color = "black";
    }
    else{
        if(hours < 12){
            hours += 12;
        }
        bodyElement.style.backgroundImage = 'url("../img/pm/5.png")';
        color = "white";
    }
}

//可以切换上午和下午，同时调整背景
function switchtime(){
    option = true;
    ischange = ischange ? false : true;
    time = (time == "am") ? "pm" : "am";
    // console.log(time);
    settime();
}

//设置闹钟来提醒用户，时间到了
function setclock(){
    var clocktime = [];
    if(time == "am"){
        clocktime.push(hours);
        clocktime.push(minutes);        
    }
    else {
        clocktime.push(hours % 12+12);
        clocktime.push(minutes);

    }
    clocklist.push(clocktime);
    showclock();
    alert("添加闹钟成功");
    option = false;
}

//设置固定时间
function setclock2(n){

    now = new Date();
    var clocktime = [];
    var hour = now.getHours();
    var minute = now.getMinutes();
    if(n == 60){
        hour = (hour + 1) % 24;
        clocktime.push(hour);
        clocktime.push(minute);
    }
    else if(n == 30 && minute >= 30){
        hour = (hour + 1) % 24;
        clocktime.push(hour);
        clocktime.push(minute - 30);
    }
    else if (n == 30 && minute < 30){
        clocktime.push(hour);
        clocktime.push(minute + 30);
    }
    clocklist.push(clocktime);
    showclock();
    alert("添加闹钟成功");
    option = false;

}
//判断闹钟时间是否到达
function judgeclock(){
    for(var i = 0; i < clocklist.length; i++){
        if (hours == clocklist[i][0] && minutes == clocklist[i][1]){
            var music = document.getElementById("clockmusic");
            music.play();
            // console.log(clocklist[i]);
            clocklist.splice(i,1);
            showclock();
        }
    }
}

//将闹钟显示到右边板块
function showclock(){
    var html = "";
    for(var i = 0; i < clocklist.length; i++){
        html += "<div class='clock'>"+ 
                    "<p>" + clocklist[i][0] + " : " + clocklist[i][1] + "</p>"+
                    "<button id='clock" + i + "' onclick='deleteclock("+i+")'>取消闹钟</button>"+
                "</div>";
        
        // console.log(clocklist[i]);
    }
    $("#clocklist").html(html);
}

//删除闹钟
function deleteclock(n){
    clocklist.splice(n,1);
    showclock();
}

canvas.addEventListener("mousedown",ismouseonhands)
canvas.addEventListener("mousemove",mousemove)
canvas.addEventListener("mouseup",stopdrag)

settime();
update();